package com.master.demo.example.socket;

import java.io.*;
import java.net.Socket;

/**
 * socket案例
 *
 * @author: Yang
 * @date: 2021/11/27
 * @version: 1.0.0
 * Copyright Ⓒ 2021 Master Computer Corporation Limited All rights reserved.
 */
public class SocketExample {

    public static void main(String[] args) {
        try {
            // 和服务器创建连接
            Socket socket = new Socket("192.168.59.198", 4001);
            // 要发送给服务器的信息
            OutputStream os = socket.getOutputStream();
            PrintWriter pw = new PrintWriter(os);
            pw.println(getInfo());
            //flush方法是用于将输出流缓冲的数据全部写到目的地。
            //所以一定要在关闭close之前进行flush处理，即使PrintWriter有自动的flush清空功能
            pw.flush();
            socket.shutdownOutput();
            // 从服务器接收的信息
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String info = null;
            while ((info = br.readLine()) != null) {
                System.out.println("我是客户端，服务器返回信息：" + info);
            }
            br.close();
            is.close();
            os.close();
            pw.close();
            socket.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    private static String getInfo() {
        return "!0V1602A9901602000200100000000899000000000000000000000000000000000000000000000000B1657423431413254C1657423431413254D1657423431413254E";
    }

}
